<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formData['id'] || formData['nodeNameEn']"
    :append-to-body="true"
    :width="500"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <super-form
      :formAndTable="false"
      ref="mapNodeRef"
      v-bind="formConfig"
      :modelValue="formData"
      :rules="formRules"
      :disabled="props.disabled"
      @change="handleFormChange"
    >
      <!-- <template v-if="props.disabled" #release>
        <el-form-item label="状态">
          <div class="w-full flex justify-between">
            <el-input :placeholder="formData.released === 0 ? '占用' : '空闲'" type="text" disabled />
            <div
              class="h-full w-[100px] rounded-1 flex-center text-[#fff] cursor-pointer"
              :style="{
                color: formData.released === 0 ? '#fff' : 'var(--el-disabled-text-color)',
                background: formData.released === 0 ? 'var(--el-color-primary)' : 'var(--el-disabled-bg-color)',
              }"
              @click="formData.released === 0 ? releasedClick() : ''"
            >
              释放
            </div>
          </div>
        </el-form-item>
      </template> -->
    </super-form>
    <template v-if="!props.disabled" #footer>
      <div class="dialog-footer">
        <el-button @click="showDialog(false)"> 取 消 </el-button>
        <el-button type="primary" :loading="loading" @click.stop="handleSubmit" @keyup.enter="handleSubmit">
          确 定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts" name="dialogNodeAndEdge">
import { NodeFormData, EdgeFormData } from "./config";
// import { MapNode, UpdateEdge } from "@/api/map/types";
import { cloneDeep } from "lodash-es";
import { filterKey } from "@/utils/index";
// import { getNodes } from "@/utils/antvX6/nodes";
// import { getEdges } from "@/utils/antvX6/edges";
// import { useDictionaryStore } from "@/store/modules/dictionary";
import { FormItem } from "@/components/SuperForm/formType";
// import { getSelectDeviceByType } from "@/api/device/index";
// import { setNodeRelease, setEdgeRelease } from "@/api/map/index";
// import { drawUnLockNodesPath, drawUnLockEdgesPath } from "@/utils/antvX6/drawResourcesPath";
// import { useConfirm } from "@/hooks/useConfirm";
import { mapNodeType } from "@/enums/MenuTypeEnum";
// import { getChildrenByParentIds } from "@/utils/treeUtil";
// const dictionaryStore = useDictionaryStore();
import { updateNodes, updateEdges } from "@/utils/antvx6/nodeAndEdgeUpdate";
const props = withDefaults(
  defineProps<{
    disabled: false;
    mapId: -1;
  }>(),
  {}
);
const emit = defineEmits<{
  submit: [res: any];
}>();
const mapNodeRef = ref();
const loading = ref<boolean>(false);
const dialogVisible = ref<boolean>(false);
const nodeShape = ref<string>("node-point");
let nodeForm: EdgeFormData | NodeFormData | null = null;
const formData = ref<any>({});
const formConfig = ref({});
const formRules = ref({});

const showDialog = (isShow: boolean, data?: any) => {
  loading.value = false;
  if (isShow && data) {
    nodeShape.value = data.shape;
    nodeShape.value === "edge" ? (nodeForm = new EdgeFormData()) : (nodeForm = new NodeFormData());
    // nodeForm.getFormOption({ mapId: props.mapId }).finally(() => {
    formConfig.value = nodeForm?.formOption as object;
    formData.value = nodeForm?.formData as object;
    formRules.value = nodeForm?.formRules as object;
    Object.assign(formData.value, data);
    if (nodeShape.value === "node-point") {
      handleFormChange({ field: "mapNodeType" });
      handleFormChange({ field: "hasDirection" });
      //     handleFormChange({ field: "rotateType" });
      //     handleFormChange({ field: "seriesId" }, true);
    }
    dialogVisible.value = isShow;
    // });
  } else {
    dialogVisible.value = isShow;
    formData.value = {};
    mapNodeRef.value?.ruleFormRef?.resetFields();
  }
};
// 表单组件数据回调
const handleFormChange = (e: FormItem | any, isbool?: boolean) => {
  if (e.field === "mapNodeType") {
    const formItem = formConfig.value["formItems"].find((item: FormItem) => item.field === "mapNodeType");
    formItem.options = mapNodeType.filter((item) => (props.disabled ? item : item.value !== 100));
    formConfig.value["formItems"].forEach((item: any) => {
      if (Array.isArray(item.mapNodeType)) {
        item.isHidden = !item.mapNodeType.some((subItem: number) => subItem === Number(formData.value["mapNodeType"]));
        if (item.isHidden) {
          formData.value[item.field] = null;
        }
      }
      // if (Array.isArray(item.rotateType)) {
      //   item.isHidden = !item.rotateType.some((subItem: number) => subItem === Number(formData.value["rotateType"]));
      //   if (item.isHidden) {
      //     formData.value[item.field] = null;
      //   }
      // }
    });
    // if ([5, 6, 1, 3, 4].includes(formData.value["mapNodeType"])) {
    //   const deviceId = formConfig.value["formItems"].find((item: FormItem) => item.field === "deviceId");
    //   deviceId.options = [];
    //   let deviceTypes: string = "";
    //   [1].includes(formData.value["mapNodeType"]) && (deviceTypes = "5");
    //   [3, 4].includes(formData.value["mapNodeType"]) && (deviceTypes = "3");
    //   [5, 6].includes(formData.value["mapNodeType"]) && (deviceTypes = "4");

    //   // getSelectDeviceByType({ deviceTypes, page: 1, limit: 1000 }).then((res: any) => {
    //   //   const items = res.devices.items;
    //   //   if (items.length) {
    //   //     formData.value["productName"] = items[0].productName;
    //   //     deviceId.options = items.map((item: any) => {
    //   //       return {
    //   //         label: item.deviceName,
    //   //         value: item.deviceId,
    //   //       };
    //   //     });
    //   //   } else {
    //   //     formData.value["deviceId"] = null;
    //   //     if (deviceTypes === "5") {
    //   //       formData.value["productName"] = "充电设备";
    //   //     } else if (deviceTypes === "3") {
    //   //       formData.value["productName"] = "门";
    //   //     } else if (deviceTypes === "4") {
    //   //       formData.value["productName"] = "电梯";
    //   //     }
    //   //   }
    //   // });
    // }
    // if ([2].includes(formData.value["mapNodeType"])) {
    //   formData.value["priorityNode"] = 0;
    // }
  } else if (e.field === "hasDirection") {
    const angle = formConfig.value["formItems"].find((item: FormItem) => item.field === "angle");
    angle.isHidden = !(formData.value["hasDirection"] === 1);
    if (angle.isHidden) {
      formData.value[angle.field] = 0;
    }
  } 
  // else if (e.field === "rotateType") {
  //   formConfig.value["formItems"].forEach((item: any) => {
  //     if (Array.isArray(item.rotateType)) {
  //       item.isHidden = !item.rotateType.some((subItem: number) => subItem === Number(formData.value["rotateType"]));
  //       if (item.isHidden) {
  //         formData.value[item.field] = null;
  //       }
  //     }
  //   });
  // }
};

const handleSubmit = () => {
  loading.value = true;
  mapNodeRef.value.ruleFormRef.validate((valid: any) => {
    if (valid) {
      const callback = () => {
        loading.value = false;
        showDialog(false);
        ElMessage.success("操作成功");
      };
      const _row = filterKey(cloneDeep(formData.value));
      if (nodeShape.value === "node-point") {
        updateNodes(_row).then((res) => callback());
      } else {
        updateEdges(_row).then((res) => callback());
      }
    } else {
      loading.value = false;
    }
  });
};

// 手动释放节点、边
// const releasedClick = async () => {
//   const fn: any = nodeShape.value === "edge" ? setEdgeRelease : setNodeRelease;
//   const params = nodeShape.value === "edge" ? { edgeId: formData.value.edgeId } : { nodeId: formData.value.nodeId };
//   const { showConfirm } = useConfirm(
//     "警告",
//     `是否确认释放当前${nodeShape.value === "edge" ? "边" : "节点"}，释放后不可以恢复？`
//   );
//   const confirmed = await showConfirm();
//   if (confirmed) {
//     fn(params).then((res: any) => {
//       if (res?.edgeId || res?.nodeId) {
//         const list: any =
//           nodeShape.value === "edge"
//             ? [
//                 {
//                   startNodeId: 0,
//                   edgeId: res.edgeId,
//                   edgeName: "",
//                   endNodeId: 0,
//                 },
//               ]
//             : [
//                 {
//                   mapId: 0,
//                   mapNodeId: res.nodeId,
//                   nodeNameEn: "",
//                 },
//               ];
//         nodeShape.value === "edge" ? drawUnLockEdgesPath(list) : drawUnLockNodesPath(list);
//         ElMessage.success("操作成功");
//       }
//     });
//   }
// };

defineExpose({
  showDialog,
});
</script>
